#!/usr/bin/python
import sys
import importlib
importlib.reload(sys)
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams

def pdf_process(path):
    # 以二进制形式打开pdf文件
    with open(path, "rb") as f:
        # 创建一个pdf文档分析器
        parser = PDFParser(f)
        # 创建pdf文档
        pdfFile = PDFDocument()
        # 链接分析器与文档对象
        parser.set_document(pdfFile)
        pdfFile.set_parser(parser)
        # 提供初始化密码
        pdfFile.initialize()
    if not pdfFile.is_extractable:
        return []
    else:
        # 解析数据
        # 数据管理
        manager = PDFResourceManager()
        # 创建一个PDF设备对象
        laparams = LAParams()
        device = PDFPageAggregator(manager, laparams=laparams)
        # 解释器对象
        interpreter = PDFPageInterpreter(manager, device)
        # 开始循环处理，每次处理一页
        results = []
        context_id = 0
        for page in pdfFile.get_pages():
            interpreter.process_page(page)
            # 使用聚合器来获得内容
            layout = device.get_result()
            for x in layout:
                if type(x) == LTTextBoxHorizontal:
                    line = x.get_text()
                    if len(line) > 5:
                        temp = {}
                        context_id += 1
                        temp["context_id"] = context_id
                        temp["context"] = line
                        results.append(temp)
    return results
